from django.contrib.auth.hashers import check_password, make_password
from django.contrib.auth.models import User
from rest_framework import serializers
from rest_framework.response import Response

from v1.models import Provincial, AreaManage, Image
import  uuid

class ProvincialSerializer(serializers.ModelSerializer):
    child = serializers.SerializerMethodField()
    manageinfo = serializers.SerializerMethodField()
    # code = serializers.CharField(max_length=20, write_only=True)


    class Meta:
        model = Provincial
        # fields = '__all__'
        fields = ['id','Pr_name','parent','user','manageinfo','child']
    def get_child(self,obj):
        return ProvincialSerializer(obj.children.all(),many=True).data

    def get_manageinfo(self,obj):
        us = obj.user
        se = UserSerializer(us,many=False).data
        return {"管理员信息":se["username"],"管理员密码":se['password'][0:5]+"..."}


    # def create(self, validated_data):
    #     # 用Django ORM的操作将视图层传来的数据新增到数据库
    #     ret = Provincial.objects.create(**validated_data)
    #     return ret




class UserSerializer(serializers.ModelSerializer):
    oldpassword = serializers.CharField(default='',max_length=100,write_only=True)
    class Meta:
        model = User
        fields = ['id','username','password','oldpassword']
        # fields = '__all__'


    def create(self, validated_data):
        validated_data['password'] = make_password(validated_data['password'], None, 'pbkdf2_sha256')
        return super().create(validated_data)


    def update(self, instance, validated_data):
        validated_data['password'] = make_password(validated_data['password'], None, 'pbkdf2_sha256')
        return super().update(instance,validated_data)



    def validate(self, attrs):
        """如果attrs['oldpassword'为空,执行添加，如果有值，则修改
        """
        if attrs['oldpassword']!='':
            if check_password(attrs['oldpassword'],self.instance.password,'pbkdf2_sha256'):
                del attrs['oldpassword']
                return attrs
            else:
                raise serializers.ValidationError("旧密码验证失败")
        else:
            del attrs['oldpassword']
            return attrs



class AreaSerializer(serializers.ModelSerializer):
    child = serializers.SerializerMethodField()
    image = serializers.SerializerMethodField(read_only=True)
    # user1 = serializers.SerializerMethodField()
    class Meta:
        model = AreaManage
        # fields = '__all__'
        fields = ['id','Pr_name','parent','image','child','user']

    def get_child(self, obj):
        return AreaSerializer(obj.children.all(), many=True).data
    #
    def get_user1(self, obj):
        return UserSerializer(obj.user.all(), many=True).data

    def get_image(self, obj):
        return ImageSerializer(Image.objects.filter(area_id=obj.id).all(), many=True).data



class ImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = Image
        fields = ['id','area_id','image_url']



